from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from model import Student, CourseNew

# 1. 链接数据库等准备工作
engine = create_engine('mysql+pymysql://root:python@localhost:3306/19python')
DBSession = sessionmaker(bind=engine)
session = DBSession()

# 2. 查询数据
# 查询 学生id为2的名字和他的选课
stu02 = session.query(Student).filter(Student.sid == 2).one()
print(stu02.name)
courses02 = stu02.courses
for course in courses02:
    print(course.name)

print('--------------------------------------------------------------')
# 查询id为1的课程，都有哪些学生选了它
course01 = session.query(CourseNew).filter(CourseNew.cid == 1).one()
print(course01.name)
stus01 = course01.stus
for stu in stus01:
    print(stu.name)

# 3. 关闭session
session.close()
